package com.atguigu.reggie.controller;

import com.atguigu.reggie.common.BaseContext;
import com.atguigu.reggie.common.R;
import com.atguigu.reggie.dto.DishDto;
import com.atguigu.reggie.dto.SetmealDto;
import com.atguigu.reggie.entity.Category;
import com.atguigu.reggie.entity.Dish;
import com.atguigu.reggie.entity.Setmeal;
import com.atguigu.reggie.entity.SetmealDish;
import com.atguigu.reggie.service.CategoryService;
import com.atguigu.reggie.service.DishService;
import com.atguigu.reggie.service.SetmealDishService;
import com.atguigu.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-10-21 16:33
 */

/**
 * 套餐管理
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation("新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("套餐信息：{}",setmealDto);

        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true),
            @ApiImplicitParam(name = "name", value = "套餐名称", required = false)
    })
    public R<Page> page(int page,int pageSize,String name){
        // 分页构造器对象
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        // 查询构造器
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件，根据name进行like模糊查询,根据跟新时间来降序排列
        setmealLambdaQueryWrapper.like(name != null,Setmeal::getName,name).orderByDesc(Setmeal::getUpdateTime);

        // 通过service进行查询
        setmealService.page(setmealPage,setmealLambdaQueryWrapper);

        // 进行对象拷贝
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");

        // 对得到的records集合进行拷贝
        List<Setmeal> setmeals = setmealPage.getRecords();

        List<SetmealDto> setmealDtos = setmeals.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            // 对象拷贝
            BeanUtils.copyProperties(item,setmealDto);
            Category category = categoryService.getById(item.getCategoryId());

            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }

            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(setmealDtos);

        return R.success(setmealDtoPage);
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids){
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
    }


    @PostMapping("/status/{status}")
    @CacheEvict(value = {"singleSetmealCache","setmealCache"},allEntries = true)
    public R<String> status(@PathVariable("status") int status,@RequestParam("ids") List<Long> ids){
        // 创建查询构造器
        // UpdateWrapper<Setmeal> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<Setmeal> setmealLambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        // 添加条件
        setmealLambdaUpdateWrapper.in(Setmeal::getId,ids).set(Setmeal::getStatus,status);
        setmealLambdaUpdateWrapper.set(Setmeal::getUpdateTime, LocalDateTime.now()).set(Setmeal::getUpdateUser, BaseContext.getCurrentId());
        // updateWrapper.in("id",ids).set("status",status);

        setmealService.update(setmealLambdaUpdateWrapper);

        return R.success("修改成功");
    }

    /**
     * 根据条件查询套参数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId +'_'+ #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        // 创建查询构造器
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        setmealLambdaQueryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        // 进行查询
        List<Setmeal> list = setmealService.list(setmealLambdaQueryWrapper);

        return R.success(list);
    }

    /**
     * 根据id查询菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id){
        // 通过id查询dishDto信息
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = {"singleSetmealCache","setmealCache"},allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithDish(setmealDto);
        return R.success("修改成功");
    }


    /**
     * 展示套餐中的菜品以及对应数量
     * @param setmealId
     * @return
     */
    @GetMapping("/dish/{setmealId}")
    @Cacheable(value = "singleSetmealCache",key = "#setmealId")
    public R<List<DishDto>> dishList(@PathVariable("setmealId") Long setmealId){
        // 创建查询
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,setmealId);
        List<SetmealDish> list = setmealDishService.list(setmealDishLambdaQueryWrapper);
        List<DishDto> dishDtos = list.stream().map((item) -> {
            // 先拷贝item中的copies
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            // 查询对应dishId的dish并拷贝到dishDto
            Dish dish = dishService.getById(item.getDishId());
            BeanUtils.copyProperties(dish,dishDto);

            return dishDto;

        }).collect(Collectors.toList());

        return R.success(dishDtos);
    }




}
